<template>
  <div
    v-loading.fullscreen.lock="seeLoading"
    class="add-excel"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-button type="primary" @click="addNewTable('addTable')">新增表格</el-button>
    <div class="content">
      <div class="addCheck item">
        <el-card style="width:30%">
          <el-table
            :data="deptList"
            row-key="deptId"
            default-expand-all
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="deptName" label="部门名称" />
            <el-table-column prop="deptNum" label="部门编号" />
          </el-table>
        </el-card>
        <el-card style="width:60%;height:750px">
          <el-table :data="tableList" class="ct" height="650">
            <el-table-column prop="tableName" label="表名" width="180" fixed />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="createBy" label="创建人" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column prop="remark" label="操作" fixed="right">
              <template slot-scope="scope">
                <div style="display: flex;">
                  <el-button v-no-more-click type="text" @click="seeTable(scope.row,'updateTable')">查看
                  </el-button>
                  <el-button
                    v-no-more-click
                    style="float: right; padding: 3px 0;color:red"
                    type="text"
                    @click="deleteTable(scope.row)"
                  >删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getTableList"
          />
        </el-card>
      </div>
    </div>
    <el-drawer
      v-if="dialogFormVisible"
      :title="addForm.is == 'addTable'?'新增':'编辑'+'表格'"
      :visible.sync="dialogFormVisible"
      direction="rtl"
    >
      <el-form ref="form" :model="addForm" label-width="120px" style="padding:10px">
        <el-form-item label="表格名称">
          <el-input v-model="addForm.tableName" clearable style="width:500px" @change="inputChange" />
        </el-form-item>
        <el-form-item label="否是显示级别">
          <el-switch v-model="addForm.isType" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入内容" style="width:500px" />
        </el-form-item>
        <el-form-item label="参数设置">
          <!-- <div>预览</div> -->
          <div v-for="(item,index) in cssz" :key="index" class="cssz-item">
            <el-divider>{{ item.tips }}</el-divider>
            <div class="item-lable">
              <span>是否显示：</span>
              <el-switch v-model="item.isShow" />
            </div>
            <div class="item-lable">
              <span>是否必填</span>
              <el-switch v-model="item.isUp" />
            </div>
            <div class="item-lable">
              <span>回显名称：</span>
              <el-input v-model="item.tips" clearable style="width:300px" />
            </div>
            <div class="item-lable">
              <span>回显提示：</span>
              <el-input v-model="item.placeholder" clearable style="width:300px" />
            </div>
            <div v-if="item.name == 'dictCode'" class="item-lable">
              <span>是否显示子项验证：</span>
              <el-switch v-model="item.isChildren" inactive-text="子项验证" />
            </div>
            <div v-if="item.name == 'dictCode' && item.isChildren" style="display: flex; flex-direction: column;">
              <div>
                <span>需要显示的值：</span>
                <el-input
                  v-model="item.children.value"
                  clearable
                  style="width:300px"
                  @input="$event=>valueChange($event,index)"
                />
              </div>
              <div>
                <span>回显名称：</span>
                <el-input v-model="item.children.tips" clearable style="width:300px" />
              </div>
              <div>
                <span>回显提示：</span>
                <el-input v-model="item.children.placeholder" clearable style="width:300px" />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="抽点单位">
          <el-table
            ref="multipleTable"
            class="table-el"
            :data="deptList"
            row-key="deptId"
            tooltip-effect="dark"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="handleSelectionChange"
            @cell-dblclick="cellDblclick"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="deptName" label="部门名称" />
            <el-table-column label="级别人数" width="180">
              <template slot-scope="scope">
                <div class="jb">
                  <div v-if="scope.row.deptType">{{ scope.row.deptType }}</div>
                  <div v-if="scope.row.zbrs">{{ scope.row.zbrs }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="deptNum" label="部门编号" />
          </el-table>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-no-more-click type="primary" @click="addFormSave">{{ addForm.is == 'addTable'?'保存':'更新' }}
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  mixins
} from '../xsqpcs'
import {
  addTable,
  updateTable
} from '@/api/rhtx/ExcelTable'
import {
  listDept
} from '@/api/system/dept'
import {
  listTable,
  getTableEx,
  delTable
} from '@/api/rhtx/ExcelTable'
import {
  pinyin
} from 'pinyin-pro'
export default {
  mixins: [mixins],
  data() {
    return {
      cssz: [{
        name: 'name',
        isShow: false,
        tips: '被点检人姓名',
        type: 'input',
        placeholder: '请输入被点检人姓名',
        isUp: false
      }, {
        name: 'deptId',
        isShow: false,
        tips: '被点检单位',
        type: 'select',
        placeholder: '请选择被点检单位',
        isUp: false
      }, {
        name: 'dictCode',
        isShow: false,
        tips: '点检结果',
        type: 'select',
        placeholder: '请选择点检结果',
        isUp: false,
        isChildren: false,
        children: {
          value: undefined,
          name: 'wgsj',
          tips: '违规时间区间',
          type: 'dates',
          isUp: false,
          placeholder: '违规请选择时间区间'
        }
      }, {
        name: 'jgms',
        isShow: false,
        tips: '结果描述',
        type: 'textarea',
        placeholder: '请输入结果描述',
        isUp: false
      }, {
        name: 'djr',
        isShow: false,
        tips: '点检人',
        type: 'select',
        isUp: false,
        placeholder: '请选择点检人'
      }, {
        name: 'cddw',
        isShow: false,
        tips: '点检单位',
        type: 'select',
        isUp: false,
        placeholder: '请选择点检单位'
      }, {
        name: 'lrTime',
        isShow: false,
        tips: '点检时间',
        type: 'date',
        isUp: false,
        placeholder: '请选择点检时间'
      }, {
        name: 'remark',
        isShow: false,
        tips: '备注',
        type: 'input',
        isUp: false,
        placeholder: '请输入备注'
      }, {
        name: 'remark',
        isShow: false,
        tips: '备注',
        type: 'input',
        isUp: false,
        placeholder: '请输入备注'
      }],
      total: 0,
      seeLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      dialogFormVisible: false,
      deptList: [],
      addForm: {
        isType: 0,
        tableName: '',
        szm: '',
        is: 'addTable',
        remark: ''
      },
      addFormList: [],
      tableList: []
    }
  },
  created() {
    this.getTableList()
    this.getDept()
  },
  methods: {
    valueChange(value, index) {
      if (!value) {
        this.cssz[index].children.value = undefined
      }
    },
    cellDblclick(row) {
      const arr = this.forChildren(this.deptList, row.children)
      this.$nextTick(() => {
        arr.forEach(item => {
          this.$refs.multipleTable.toggleRowSelection(item)
        })
      })
    },
    getTableList() {
      listTable(this.queryParams).then(res => {
        this.tableList = res.rows
        this.total = res.total
      })
    },
    /** 查询部门列表 */
    getDept() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, 'deptId')
      })
    },
    handleSelectionChange(val) {
      this.addFormList = []
      const arr = []
      JSON.parse(JSON.stringify(val)).forEach(item => {
        if (item.children) {
          item.children = undefined
        }
        arr.push(item)
      })
      this.addFormList = arr
    },
    addNewTable(is) {
      this.addFormList = []
      this.addForm = this.$options.data().addForm
      this.cssz = this.$options.data().cssz
      this.addForm.is = is
      this.dialogFormVisible = true
    },
    // 删除表格
    deleteTable(val) {
      this.$alert('确定删除表格' + val.tableName, '删除', {
        confirmButtonText: '删除',
        callback: action => {
          delTable(val.tableId).then(res => {
            this.getTableList()
            this.$message({
              message: res.msg,
              type: 'success'
            })
          })
        }
      })
    },
    forChildren(list, cList) {
      let arr = []
      const pArr = list.filter(fItem => cList.some(sItem => fItem.deptId === sItem.deptId))
      if (pArr.length > 0) {
        arr = arr.concat(pArr)
      }
      list.forEach(item => {
        if (item.children) {
          const cArr = this.forChildren(item.children, cList)
          if (cArr.length > 0) {
            arr = arr.concat(cArr)
          }
        }
      })
      return arr
    },
    // 查看表格
    seeTable(val, is) {
      this.seeLoading = true
      getTableEx(val.tableId).then(res => {
        Object.keys(this.addForm).forEach(item => {
          this.addForm[item] = val[item]
        })
        const arr = this.forChildren(this.deptList, res.data.depts)
        this.addForm.is = is
        this.addForm.tableId = res.data.tableId
        this.addForm.isType = res.data.isType
        const cssz = JSON.parse(res.data.cssz)
        this.cssz = this.cssz.map(item => {
          const matchedItem = cssz.find(csszItem => csszItem.name === item.name)
          let newObj = {}
          if (matchedItem) {
            Object.keys(item).forEach(m => {
              newObj[m] = matchedItem[m] ? matchedItem[m] : item[m]
            })
          } else {
            newObj = item
          }
          return newObj
        })
        console.log(this.cssz)
        this.dialogFormVisible = true
        this.$nextTick(() => {
          arr.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item)
          })
        })
      }).finally(f => {
        this.seeLoading = false
      })
    },

    inputChange(val) {
      this.addForm.szm = pinyin(val, {
        pattern: 'first',
        toneType: 'none'
      }).replaceAll(' ', '')
    },
    addFormSave() {
      const api = {
        addTable,
        updateTable
      }
      const params = {
        ...this.addForm
      }
      params['cddw'] = []
      this.addFormList.forEach(item => {
        params['cddw'].push(item.deptId)
      })
      if (params.cddw.length === 0) {
        return this.$message({
          message: '请选择单位',
          type: 'error'
        })
      }
      const arr = JSON.parse(JSON.stringify(this.cssz)).filter(item => item.isShow)
      params['cssz'] = JSON.stringify(arr)
      api[params.is](params).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.addFormList = []
        this.addForm = this.$options.data().addForm
        this.$refs.multipleTable.clearSelection()
        this.dialogFormVisible = false
        this.getTableList()
      })
    }
  }
}

</script>
<style lang="scss" scoped>
  .add-excel {
    padding: 20px;

    ::v-deep .rtl {
      width: 40% !important;
    }

    .dialog-footer {
      position: fixed;
      bottom: 0;
      z-index: 2;
    }

    .item-lable {
      margin: 5px;

      .cssz-item {
        display: flex;
        align-items: center
      }
    }

    .ct {
      .cell {
        display: flex;
      }
    }

    .table-el {
      max-height: 500px;
      overflow-y: auto
    }

    .content {
      width: 100%;
      padding: 20px 0;

      .addForm {
        display: flex;
      }

      .addCheck {
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-content: flex-start;
        width: 100%;
      }

      .transfer {
        margin-right: 40px;
      }

      .noun {
        margin-left: 40px;
      }
    }
  }

</style>
